﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using Serilog.Core;
using Serilog.Events;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace TransformerManager.API.LogSettings
{
    public class HttpContextEnricher : ILogEventEnricher
    {
        private readonly IServiceProvider _serviceProvider;
        private readonly HttpContext _httpContext;

        public HttpContextEnricher(IServiceProvider serviceProvider , HttpContext httpContext)
        {
            _serviceProvider = serviceProvider;
            _httpContext = httpContext;
        }

        public async void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
        {

            if (null != _httpContext)

            {
                // 此处过滤下ExecutingEndpoint，让ExecutingEndpoint记录不存储到MSSQL中
                var value = logEvent.Properties.Values
                    .Where(t => t.ToString().Contains("ExecutingEndpoint"));
                if (value.Count() > 0) return;

                logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("OperationType", 
                    _httpContext.Request.Method));

                var userName = _httpContext.User.Identity.IsAuthenticated ?
                    _httpContext.User.Identity.Name : "unknown";
                logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("UserName",
                    userName));

                var ip = _httpContext.Connection.RemoteIpAddress.ToString();
                logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("IP",
                    !string.IsNullOrEmpty(ip) ? ip : "unknown"));

                logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("RequestPath", 
                    _httpContext.Request.Headers["Referer"]));

                _httpContext.Request.EnableBuffering();
                var reader = new StreamReader(_httpContext.Request.Body);
                var body = await reader.ReadToEndAsync();
                logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("RequestBody",
                    !string.IsNullOrEmpty(body)? body : null));
                _httpContext.Request.Body.Position = 0;

            }
        }


    }
}
